package xyz.liuz.edb;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;

import java.util.Date;
import java.util.List;

/**
 * 使用 FrameDecoder时需要考虑到读到的数据有可能是不完整的，而使用ReplayingDecoder就可以假定读到了全部的数据
 * */
public class ServiceProtocolDecoder extends ReplayingDecoder<Void> {
	@Override
	protected void decode(ChannelHandlerContext paramChannelHandlerContext,
			ByteBuf paramByteBuf, List<Object> paramList) throws Exception {
		System.out.println("解码器运行啦");
//		paramByteBuf.markReaderIndex();
//		int messageType = paramByteBuf.readInt();// 消息类型
//		System.out.println("读取到的是:"+messageType);
		byte[] msgLenByte = new byte[6];
		paramByteBuf.readBytes(msgLenByte);
		int msgLength = Integer.parseInt(new String(msgLenByte,
				CharsetUtil.UTF_8));
		System.out.println("报文头长度:"+msgLength);
		int totalMsgLength = paramByteBuf.writerIndex();
		System.out.println("总可读的字节长度:"+totalMsgLength);
		int residueMsgLength = totalMsgLength-msgLength;
		System.out.println("剩余可读的字节长度:"+residueMsgLength);

//		if(paramByteBuf.readableBytes() < msgLength){
//			System.out.println("报文体长度不符" );
//			return;
//		}
		if(residueMsgLength < msgLength){
			System.out.println("报文体长度不符,暂不处理");
//			paramByteBuf.resetReaderIndex();
//			return;
//			byte[] msgByte = new byte[residueMsgLength];
//			paramByteBuf.readBytes(msgByte);
//			System.out.println("报文体为:"+new String(msgByte,CharsetUtil.UTF_8));
		}
		byte[] msgByte = new byte[msgLength];
		paramByteBuf.readBytes(msgByte);
		paramList.add(new String(msgByte, CharsetUtil.UTF_8));


	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		IdleStateEvent event = (IdleStateEvent) evt;
		System.out.println("这里也有超时的吗？"+event.state()+":::"+new Date());
		ctx.channel().close();
	}
}
